package com.czkt.controller;

import com.czkt.pojo.SysRight;
import com.czkt.pojo.SysRoleRight;
import com.czkt.pojo.vo.SysUserVo;
import com.czkt.service.ISysRightService;
import com.czkt.service.ISysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {
    @Autowired
    ISysUserService sysUserService;

    @Autowired
    ISysRightService rightService;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/login")
    public String login(){
        return "login";
    }
    @RequestMapping("/doLogin")
    public String doLogin(String usrName, String usrPassword,Boolean remeberMe, Model model, HttpSession session){
//        SysUserVo sysUserVo = sysUserService.getUserByLogin(usrName,usrPassword);
//        if (sysUserVo == null){
//            model.addAttribute("message","账号或密码错误!!!");
//            return "login";
//        } else {
//            if (remeberMe != null){
//                stringRedisTemplate.opsForValue().set("loginUser", JSON.toJSONString(sysUserVo));
//            }
//            session.setAttribute("loginUser",sysUserVo);
//            return "main";
//        }
        String errStr = stringRedisTemplate.opsForValue().get(usrName + "errorCount:");

        Integer errCount = errStr != null?Integer.parseInt(errStr):1;
        if (errCount > 5){
            model.addAttribute("message","密码错误次数过多，请一小时后重试");
            return "login";
        }



        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(usrName,usrPassword);
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);
            SysUserVo sysUserVo = (SysUserVo) subject.getPrincipal();

            //获取用户拥有的权限
            List<SysRight> roleRights = rightService.getListById(sysUserVo.getUsrRoleId());
            sysUserVo.getRole().setRights(roleRights);

            session.setAttribute("loginUser",sysUserVo);
        } catch (UnknownAccountException e){
            model.addAttribute("message","账号不存在");
            return "login";
        } catch (LockedAccountException e){
            model.addAttribute("message","用户被禁用，登录失败!");
            return "login";
        } catch (AuthenticationException e){
            model.addAttribute("message","账号或密码错误，登录失败");
            stringRedisTemplate.opsForValue().increment(usrName + "errorCount:",1);
            stringRedisTemplate.expire(usrName + "errorCount:",1, TimeUnit.HOURS);
            return "login";
        }
        //登录成功清空错误次数
        stringRedisTemplate.delete(usrName + "errorCount");
        return "main";
    }
    @RequestMapping("/logout")
    public Object logout(HttpSession session){
        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();
        return "login";
    }

    @RequestMapping("/403")
    public String unauthorized(){
        return "403";
    }
}